const express = require('express');
const userService = require('../service/user.service.js');
const back=require('../util/response');
const md5 = require('../util/md5.js');
const multer=require('multer');
var router = express.Router();
const storage=multer.diskStorage({
  destination:function (req,file,cb){
    cb(null,"public/upload");
  },
  filename:function (req,file,cb){
    cb(null,file.originalname);
  }
})
const upload=multer({storage:storage});
/* GET users listing. */
router.get('/getlist', function(req, res, next) {
  if(req.session.adminToken){
    if(req.query.token!==md5.getToken(req.session.adminToken)){
      back.jsonWrite(res, 500,"请先登录");
    }
  }
  else{
    back.jsonWrite(res, 500,"请先登录");
    return;
  }
  userService.getlist(req,(state,msg,data={},add={})=>{
    back.jsonWrite(res,state,msg,data,add);
  })
});
router.put('/doadd',upload.single('head_img'), function(req, res, next) {
  if(req.session.adminToken){
    if(req.query.token!==md5.getToken(req.session.adminToken)){
      file.remove(req.file.path)
      back.jsonWrite(res, 500,"请先登录");
    }
    else{
      userService.add(req,(state,msg,data={},add={})=>{
        back.jsonWrite(res, state,msg,data,add);
      })
    }
  }
  else{
    file.remove(req.file.path)
    back.jsonWrite(res, 500,"请先登录");
  }
});
router.get('/info', function(req, res, next) {
  if(req.session.adminToken){
    if(req.query.token!==md5.getToken(req.session.adminToken)){
      back.jsonWrite(res, 500,"请先登录");
    }
  }
  else{
    back.jsonWrite(res, 500,"请先登录");
    return;
  }
  userService.getUserAllById(req,(data,add)=>{
    back.jsonWrite(res, 200,"操作成功",data,add);
  })
});
router.put('/doedit',upload.single('head_img'),(req,res)=>{
  if(req.session.adminToken){
    if(req.query.token!==md5.getToken(req.session.adminToken)){
      back.jsonWrite(res, 500,"请先登录");
    }
  }
  else{
    back.jsonWrite(res, 500,"请先登录");
    return;
  }
  userService.updateAllUser(req,(state,msg,data,add)=>{
    back.jsonWrite(res, state,msg,data,add);
  })
});
router.post('/dologin',(req,res, next)=>{
  userService.login(req,(data,add)=>{
    back.jsonWrite(res, 200,"操作成功",data,add);
  })
})
router.get('/search',(req,res, next)=>{
  if(req.session.adminToken){
    if(req.query.token!==md5.getToken(req.session.adminToken)){
      back.jsonWrite(res, 500,"请先登录");
      return;
    }
  }
  else{
    back.jsonWrite(res, 500,"请先登录");
    return;
  }
  if(req.query.keyword){
    userService.searchUser(req,(state,msg,data,add)=>{
      back.jsonWrite(res, state,msg,data,add);
    })
  }
  else{
    userService.getlist(req,(state,msg,data,add)=>{
      back.jsonWrite(res, state,msg,data,add);
    })
  }
})
module.exports = router;
